<template>
  <DynamicList ref="rusticListTable" v-bind="rusticListColumns" @load-data="setPage">
    <template #tableTop>
      <a-space class="flex-wrap" size="small">
        <a-button
          v-if="$auth('rustic-add')"
          type="primary"
          @click="router.push('/rustic/rusticAdd')"
        >
          <PlusOutlined />
          新增
        </a-button>
      </a-space>
    </template>
  </DynamicList>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Avatar, message, Modal, Tag } from 'ant-design-vue';
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { deleteRustic, disableRustic, rusticApi } from '@/api/rustic/rustic';
  import { formatToDateTime } from '@/utils/dateUtil';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { RequestEnum } from '@/enums/httpEnum';
  import { publicPathUrl } from '@/utils/common';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';
  import { StatusEnum, statusOptions } from '@/enums/DisableEnum';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { useUserStore } from '@/store/modules/user';

  const rusticListTable = ref<any>(null);
  const router = useRouter();
  const { list, page, setPage, loading } = useRequestList({
    apiKey: rusticApi.rusticList,
    type: RequestEnum.GET,
  });
  const rusticListColumns = ref({
    columns: [
      {
        title: '序号',
        width: 50,
        align: 'center',
        dataIndex: 'index',
        fixed: 'left',
        customRender: ({ record, text, index }) => index + 1,
      },
      {
        title: '封面',
        width: 50,
        align: 'center',
        dataIndex: 'cover',
        customRender: ({ text }) => {
          return text ? <a-image width="80px" src={getFileHttpUrl(text)} /> : '-';
        },
      },
      {
        title: '乡村名',
        width: 50,
        align: 'center',
        dataIndex: 'name',
        // 启用搜索功能
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      // title: '场馆名称'：指定列的标题为“场馆名称”。
      // width: 100：设置列的宽度为 100 像素。
      // align: 'center'：设定列中内容的水平对齐方式为居中。
      // dataIndex: 'name'：指定该列展示的数据来自数据对象中的 name 属性。
      // ellipsis: true：启用文字超出部分显示省略号的功能，当内容过长时，以省略号显示。
      // fixed: 'left'：将该列固定在表格左侧，即使水平滚动时也会保持可见。
      // search: true：启用该列的搜索功能，允许用户通过该列进行数据的搜索。
      // component: ComponentsTypeEnum.Input：指定该列的展示组件为输入框，即在表格中展示场馆名称，并且可以进行编辑。
      {
        title: '地区',
        width: 50,
        align: 'center',
        dataIndex: 'address',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '简介',
        width: 80,
        align: 'center',
        dataIndex: 'briefIntro',
        ellipsis: true,
      },
      {
        title: '联系人手机号码',
        width: 50,
        align: 'center',
        dataIndex: 'mobile',
      },
      {
        title: '状态',
        width: 40,
        align: 'center',
        dataIndex: 'status',
        search: true,
        component: ComponentsTypeEnum.Select,
        componentProps: {
          options: statusOptions,
        },
        customRender: ({ record }) => {
          return (
            <a-switch
              onChange={() => updateRusticStatus(record)}
              v-model:checked={record.status}
              un-checked-value={StatusEnum.DISABLED}
              checked-value={StatusEnum.NORMAL}
              un-checked-children={'停用'}
              checked-children={'启用'}
            />
          );
        },
      },
      {
        title: '创建时间',
        width: 50,
        align: 'center',
        dataIndex: 'createTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '操作',
        width: 60,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '乡村详情',
            vIf: true,
            onClick: (record) => {
              detail(record);
            },
          },
          {
            title: '编辑',
            vIf: verifyAuth('rustic-update'),
            onClick: (record) => {
              edit(record);
            },
          },
          {
            title: '删除',
            vIf: verifyAuth('rustic-delete'),
            onClick: (record) => {
              deleteConfirmRustic(record);
            },
          },
        ],
      },
    ],
    pageParams: page,
    list,
    loading,
    columnProps: {
      bordered: true,
    },
    // 太多字段可以左右滑动
    // columnProps: {
    //   scroll: {
    //     x: 'calc(100vw - 220px)',
    //   },
    // },
  });

  const deleteConfirmRustic = async (record) => {
    Modal.confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        const res = await deleteRustic({ id: record.id });
        if (res) {
          message.success(res?.msg);
          rusticListTable.value && rusticListTable.value.resetFields();
        }
      },
    });
  };

  const updateRusticStatus = async (record: { id: number }) => {
    const res = await disableRustic({ id: record.id });
    if (res) {
      message.success(res?.msg);
      rusticListTable.value && rusticListTable.value.resetFields();
    }
  };

  const userStore = useUserStore();
  // 详情
  const detail = async (record: { id: number }) => {
    // console.info('rusticId ==>', record.id);
    const res = await userStore.enterRustic({ rusticId: record.id });
    if (res) {
      // console.info('res ==>', res);
      message.success('进入成功！');
      // location.href = `/rustic/rusticDetail?id=${record.id}`;
      // window.open(`/rustic/rusticDetail?id=${record.id}`);
      setTimeout(() => router.push(`/rustic/rusticDetail?id=${record.id}`));
    }
  };

  // 编辑
  const edit = async (record: { id: number }) => {
    const res = await userStore.enterRustic({ rusticId: record.id });
    if (res) {
      message.success('进入成功！');
      setTimeout(() => router.push(`/rustic/rusticEdit?id=${record.id}`));
    }
  };
</script>

<style></style>
